/*
 * =============================================================================
 * "THE BEER-WARE LICENSE" (Revision 42):
 * <eirikb@google.com> wrote this file. As long as you retain this notice you
 * can do whatever you want with this stuff. If we meet some day, and you think
 * this stuff is worth it, you can buy me a beer in return Eirik Brandtzæg
 * =============================================================================
 */
package no.eirikb.roboco.terminal;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import no.eirikb.roboco.server.Server;
import no.eirikb.roboco.server.ServerAction;
import no.eirikb.roboco.server.ServerListener;
import no.eirikb.roboco.telnet.TelnetCommands;

/**
 *
 * @author eirikb
 * @author <a href="mailto:eirikb@google.com">eirikb@google.com</a>
 */
public class TerminalServer implements ServerAction {

    private List<Server> servers;
    private Hashtable<Server, Terminal> terminalList;
    private ServerListener listener;

    public static void main(String[] args) {
        new TerminalServer(13356);
    }

    public TerminalServer(int port) {
        try {
            servers = new ArrayList<Server>();
            terminalList = new Hashtable<Server, Terminal>();
            listener = new ServerListener(this, port);
            listener.start();
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void close() {
        listener.close();
        for (Server server : servers) {
            server.close();
        }
    }

    public void onServerConnect(Server server) {
        servers.add(server);

        for (int i : TelnetCommands.CBREAK) {
            try {
                server.getSocket().getOutputStream().write(i);
            } catch (IOException ex) {
                Logger.getLogger(TerminalServer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        for (int i = 0; i < TelnetCommands.CBREAK.length; i++) {
            try {
                server.getSocket().getInputStream().read();
            } catch (IOException ex) {
                Logger.getLogger(TerminalServer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        initTerminal(server, "welcome");
    }

    public void initTerminal(Server server, String term) {
        Terminal terminal = new Terminal(this, term, server);
        terminal.runProgram("index");
        terminalList.put(server, terminal);
    }

    public void onServerDisconnect(Server server) {
        System.out.println("Disconnect: " + server.getIP());
        servers.remove(server);
        terminalList.remove(server);
    }

    public void onServerRead(Server server, int c) {
        terminalList.get(server).read(c);
    }
}
